﻿using System;
using System.Collections.Specialized;
using Loki.Commands;
using Loki.Utils;
using Luna.Model.Budget;

namespace Luna.UI.Budget
{
    public class BudgetListViewModel : LunaViewModel
    {
        public BudgetListViewModel()
        {
            Budgets = CreateCollection<DisplayableBudget>();

            Init += BudgetListViewModel_Init;
            Load += BudgetListViewModel_Load;
        }

        public LokiCollection<DisplayableBudget> Budgets { get; private set; }

        private void Application_New_Execute(object P_Sender, CommandEventArgs e)
        {
            var L_NewBudget = ApplicationModel.Create<IEditableBudget>();
            ApplicationCommands.OPEN.Execute(L_NewBudget);
        }

        private void BudgetListViewModel_Init(object P_Sender, EventArgs e)
        {
            Commands.Handle(ApplicationCommands.NEW, Application_New_Execute);
        }

        private void BudgetListViewModel_Load(object P_Sender, EventArgs e)
        {
            LoadData();
            this.WatchCollectionChange(ApplicationModel.Budget.Budgets, v => v.Model_BudgetList_Changed);
        }

        private void LoadData()
        {
            Budgets.BeginInit();

            Budgets.Clear();

            foreach (var L_Budget in ApplicationModel.Budget.Budgets)
            {
                DisplayableBudget L_Display = new DisplayableBudget();
                L_Display.BeginInit();

                L_Display.EndInit();
                Budgets.Add(L_Display);
            }

            Budgets.EndInit();
        }

        private void Model_BudgetList_Changed(object P_Sender, NotifyCollectionChangedEventArgs e)
        {
            LoadData();
        }
    }
}